package com.example.traver.service;

import com.example.traver.entity.FastGptRequest;
import com.example.traver.entity.FastGptResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
@RequiredArgsConstructor
public class FastGptService {
    @Autowired
    private WebClient fastGptWebClient;

    public Mono<FastGptResponse> sendMessage(FastGptRequest request) {
        request.setStream(false);
        request.setTemperature(0.7);

        WebClient.ResponseSpec mono=  fastGptWebClient.post()
                .uri("/v1/chat/completions")
                .bodyValue(request)
                .retrieve()
                .onStatus(
                        status -> status.is4xxClientError() || status.is5xxServerError(),
                        response -> response.bodyToMono(String.class)
                                .flatMap(error -> Mono.error(new RuntimeException("FastGPT API error: " + error))));

        return mono.bodyToMono(FastGptResponse.class);
    }

    /**
     * 流式响应支持
     */
    public Flux<String> streamChatCompletion(FastGptRequest request) {
        request.setStream(true);

        return fastGptWebClient.post()
                .uri("/v1/chat/completions")
                .bodyValue(request)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class);
    }
}